/******************************************************************************
 * This file is part of libemb.
 *
 * libemb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * libemb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with libemb.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Project: Embedme
 * Author : FergusZeng
 * Email  : cblock@126.com
 * git	  : https://gitee.com/newgolo/embedme.git
 * Copyright 2014~2020 @ ShenZhen ,China
*******************************************************************************/
#include <spdlog/sinks/rotating_file_sink.h>
#include <spdlog/fmt/bin_to_hex.h>
#include <spdlog/formatter.h>
#include "libemb/Tracer.h"
#include "libemb/FileUtil.h"
#include "libembx/SpdLogger.h"
namespace libembx{
using namespace libemb;
SpdLogger::SpdLogger()
{
}

SpdLogger::~SpdLogger()
{
}

bool SpdLogger::createLog(int logID, const std::string& logFile,uint32 limitSize,uint32 rotations)
{
    if (logFile.empty())
    {
        return false;
    }

    FilePath logPath(logFile);
    auto logDir = logPath.dirName();
    if (!Directory::exists(logDir))
    {
        if(!Directory::createDir(logDir,true))
        {
            return false;
        }
    }

    if (m_logMap.find(logID)!=m_logMap.end())
    {
        //TRACE_ERR_CLASS("log allready exist,logID:%d!\n",logID);
        return false;
    }
    try
	{
        auto logName = logPath.baseName();
        auto logger = spdlog::rotating_logger_mt(logName, logFile, limitSize, rotations);
        if (!logger)
        {
            return false;
        }
        auto log = std::make_shared<Log>();
        log->m_logger = std::move(logger);
        m_logMap.insert({logID,log});
	}
	catch(const spdlog::spdlog_ex& ex)
	{
		//TRACE_ERR_CLASS("create log[%s] error:%s\n",CSTR(logFile),ex.what());
		return false;
	}
    return true;
}

void SpdLogger::logInfo(int logID, const std::string& info)
{
    auto iter = m_logMap.find(logID);
    if (iter!=m_logMap.end())
    {
        AutoLock lock(iter->second->m_mutex);
        iter->second->m_logger->info("{}",info);
    }
}
void SpdLogger::logError(int logID, const std::string& error)
{
    auto iter = m_logMap.find(logID);
    if (iter!=m_logMap.end())
    {
        AutoLock lock(iter->second->m_mutex);
        iter->second->m_logger->error("{}",error);
    }
}

}